package com.yuan.rest.controller.admin;

import com.yuan.rest.entrity.SysRole;
import com.yuan.rest.repository.SysRoleRepository;
import com.yuan.rest.util.Result;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @Auther: SiYuan
 * @Date: 2019/3/4 16:01
 * @Description:
 */

@RestController
@RequestMapping("role")
public class RoleController {
    @Autowired
    SysRoleRepository sysRoleRepository;

    @GetMapping("/list")
    public String roleList() {
        return "admin/role_list";
    }

    /***
     *  获取用户列表  layUi 的表格数据
     * @param
     * @return
     */
    @GetMapping("/roles")
    @ResponseBody
    public Map<String, Object> getUserList() {
        return list();
    }



    /***
     * 添加角色
     * @param sysRole
     * @return
     */
    @PostMapping("add")
    @ResponseBody
    public Result addUser(@RequestBody SysRole sysRole) {
        Optional<SysRole> byId = sysRoleRepository.findById(sysRole.getRoleId());
        if (byId!=null) {
            sysRoleRepository.save(sysRole);
            return Result.ok().put("data", sysRole);
        }else {

        }
        return null;
    }

    /***
     *  删除用户
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public Result delet(@PathVariable long id) {
        sysRoleRepository.deleteById(id);
        return Result.ok();
    }

    public Map<String, Object> list() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", sysRoleRepository.findAll().size());
        map.put("data", sysRoleRepository.findAll());
        return map;
    }


    /***
     * 根据角色id 名查询角色信息
     *
     */
    @GetMapping("{id}")
    @ResponseBody
    public Result getUserInfo(@PathVariable long id){

        Optional<SysRole> byId = sysRoleRepository.findById(id);
        return Result.ok().put("data",byId);
    }

}
